package com.bbx.taxi.client.Util.FastBlur;

import java.io.File;
import java.io.FileOutputStream;

import com.baidu.mapapi.map.BaiduMap.SnapshotReadyCallback;
import com.baidu.mapapi.map.MapView;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * @Path com.bbx.taxi.client.Util.FastBlur.BlurBuilder.java
 * @Author 严旭文
 * @Date 2016-10-10 上午10:40:52
 * @Company 蓝海（福建）信息技术有限公司
 * @Description
 */
public class BlurBuilder {
	// 截图监听
	public interface OnSnapShotFinishListener {
		public void OnSnapShotFinish(boolean isSuccess);
	}

	public static OnSnapShotFinishListener mOnSnapShotFinishListener = null;

	public static void setOnSnapShotFinishListener(OnSnapShotFinishListener l) {
		mOnSnapShotFinishListener = l;
	}

	// 模糊设置监听
	public interface OnBlurFinishListener {
		public void OnBlurFinish(Drawable mDrawable);
	}

	public static OnBlurFinishListener mOnBlurFinishListener = null;

	public static void setBlurFinishListener(OnBlurFinishListener l) {
		mOnBlurFinishListener = l;
	}

	private static final float BITMAP_SCALE = 0.2f;
	private static final float BLUR_RADIUS = 7.5f;

	public static Bitmap tab_bg = null;
	private static Bitmap overlay = null;
	private static boolean blurFlag = false;

	public static boolean isBlurFlag() {
		return BlurBuilder.blurFlag;
	}

	public static void setBlurFlag(boolean blurFlag) {
		BlurBuilder.blurFlag = blurFlag;
	}

	public static Bitmap blur(Activity context, View view) {
		if (tab_bg == null) {
			android.util.Log.i("", "tab_bg == null");
			blurFlag = false;
			return null;
		}
		blurFlag = true;
		blur(context, tab_bg, view);
		return overlay;
	}

	public static void blur(Activity ctx, Bitmap image, View view) {
		long startMs = System.currentTimeMillis();
		float scaleFactor = 8;
		float radius = 20;
		DisplayMetrics dm = new DisplayMetrics();
		ctx.getWindowManager().getDefaultDisplay().getMetrics(dm);
		Bitmap overlay = Bitmap
				.createBitmap((int) (dm.widthPixels / scaleFactor),
						(int) ((dm.heightPixels - ScreenUtils
								.getStatusHeight(ctx)) / scaleFactor),
						Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(overlay);
		canvas.translate(-view.getLeft() / scaleFactor, -view.getTop()
				/ scaleFactor);
		canvas.scale(1 / scaleFactor, 1 / scaleFactor);
		Paint paint = new Paint();
		paint.setFlags(Paint.FILTER_BITMAP_FLAG);
		canvas.drawBitmap(image, 0, 0, paint);

		overlay = FastBlur.doBlurJniArray(overlay, (int) radius, true);
		if(mOnBlurFinishListener!=null)mOnBlurFinishListener.OnBlurFinish(new BitmapDrawable(ctx.getResources(), overlay));
	}

	public static void getScreenshot(View v) {
		if (tab_bg != null) {
			recycle();
		}
		try {
			tab_bg = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
					Bitmap.Config.RGB_565);
			Canvas c = new Canvas(tab_bg);
			v.draw(c);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取当前屏幕截图，不包含状态栏
	 * 
	 * @param activity
	 * @return
	 */
	public static void snapShotWithoutStatusBar(Activity activity) {
		if (tab_bg != null) {
			recycle();
		}
		View view = activity.getWindow().getDecorView();
		try {
			view.buildDrawingCache();

			// 获取状态栏高度
			Rect rect = new Rect();
			view.getWindowVisibleDisplayFrame(rect);
			int statusBarHeights = rect.top;
			Display display = activity.getWindowManager().getDefaultDisplay();

			// 获取屏幕宽和高
			int widths = display.getWidth();
			int heights = display.getHeight();

			// 允许当前窗口保存缓存信息
			view.setDrawingCacheEnabled(true);

			// 去掉状态栏
			Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(), 0,
					statusBarHeights, widths, heights - statusBarHeights);

			// 销毁缓存信息
			view.destroyDrawingCache();
			tab_bg = bmp;
		} catch (Exception e) {
			e.printStackTrace();
			getScreenshot(view);
		}
	}

	public static void recycle() {

		try {
			if (tab_bg != null) {
				tab_bg.recycle();
				System.gc();
				tab_bg = null;
			}
			if (overlay != null) {
				overlay.recycle();
				System.gc();
				overlay = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static Bitmap Bmp;

	/**
	 * 获取和保存当前屏幕的截图
	 */
	public static void GetandSaveCurrentImage(final Activity context,
			MapView mMapView) {
		// 1.构建Bitmap
		WindowManager windowManager = context.getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		int w = display.getWidth();
		int h = display.getHeight();

		// 2.获取屏幕
		final View decorview = context.getWindow().getDecorView();
		decorview.setDrawingCacheEnabled(true);
		context.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				Bmp = decorview.getDrawingCache();
			}
		});
		// 截屏百度地图
		mMapView.getMap().snapshotScope(null, new SnapshotReadyCallback() {
			@Override
			public void onSnapshotReady(Bitmap bitmap) {
				try {
					String SavePath = getSDCardPath() + "/AndyDemo/ScreenImage";
					Bitmap bitmap3 = Bitmap.createBitmap(bitmap.getWidth(),
							bitmap.getHeight(), bitmap.getConfig());
					Canvas canvas = new Canvas(bitmap3);
					canvas.drawBitmap(bitmap, new Matrix(), null);
					canvas.drawBitmap(Bmp, 0,
							-ScreenUtils.getStatusHeight(context), null); // 120、350为bitmap2写入点的x、y坐标
					tab_bg = bitmap3;
					if (mOnSnapShotFinishListener != null)
						mOnSnapShotFinishListener.OnSnapShotFinish(true);
				} catch (Exception e) {
					if (mOnSnapShotFinishListener != null)
						mOnSnapShotFinishListener.OnSnapShotFinish(false);
				}
			}
		});

	}

	private static void saveBitmap(Context context, Bitmap Bmp) {
		String SavePath = getSDCardPath() + "/AndyDemo/ScreenImage";
		// 3.保存Bitmap
		try {
			File path = new File(SavePath);
			// 文件
			String filepath = SavePath + "/Screen_1.png";
			File file = new File(filepath);
			if (!path.exists()) {
				path.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}

			FileOutputStream fos = null;
			fos = new FileOutputStream(file);
			if (null != fos) {
				Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
				fos.flush();
				fos.close();

				Toast.makeText(context,
						"截屏文件已保存至SDCard/AndyDemo/ScreenImage/下",
						Toast.LENGTH_LONG).show();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取SDCard的目录路径功能
	 * 
	 * @return
	 */
	private static String getSDCardPath() {
		File sdcardDir = null;
		// 判断SDCard是否存在
		boolean sdcardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		if (sdcardExist) {
			sdcardDir = Environment.getExternalStorageDirectory();
		}
		return sdcardDir.toString();
	}
}